package com.pwt.security.utils;

import com.pwt.security.JWTConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class JWTUtils {

    public static JWTUser getToken() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes == null) return null;
        HttpServletRequest request = (HttpServletRequest) Objects.requireNonNull(requestAttributes).resolveReference(RequestAttributes.REFERENCE_REQUEST);

        String token = request.getHeader("Authorization");
        Claims claims = Jwts.parser()
                .setSigningKey(JWTConstants.SECRET)
                .parseClaimsJws(token.replace("Bearer ", ""))
                .getBody();
        ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String, String>>) claims.get("authorities");
        List<String> strings = list.stream().map(map->map.get("authority")).collect(Collectors.toList());
        JWTUser jwtUser = new JWTUser();
        jwtUser.setUsername(claims.getSubject());
        jwtUser.setAuthorities(strings);
        return jwtUser;
    }
}
